package org.test.updownload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * 上传文件时的动作，即点击submit后，上传文件
 * Servlet implementation class Upload
 */
public class Upload extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Upload() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		response.setCharacterEncoding("utf-8");
		response.getWriter().println("请以post方式提交");

	}


	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		UploadStatus status = new UploadStatus();
		UploadListener uploadListener = new UploadListener(status);
		request.getSession(true).setAttribute("uploadstatus", status);//把statue放到session

		ServletFileUpload diskFileUpload = new ServletFileUpload(
				new DiskFileItemFactory());

		diskFileUpload.setProgressListener(uploadListener);

		// 这个线程纯粹是用来给看看status的变化的
	/*	Runnable r = new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				for (int i = 0; i < 10000; i++) {
					System.out.println(status.getBytesRead());
				}

			}
		};
		Thread t = new Thread(r);
		t.start();*/

		try {
			List<FileItem> listf = diskFileUpload.parseRequest(request);

			for (FileItem fileItem : listf) {
//				if ("file1".equals(fileItem.getFieldName())) {// 为file1
				if(!fileItem.isFormField()){ //为upload..执行
					System.out.println("文件名为：" + fileItem.getFieldName());

					// remoteFile
//					File remoteFile = new File(new String(fileItem.getName()
//							.getBytes(), "utf-8"));

									
					// new一个服务器端文件
					File file1 = new File("f:/atachment", fileItem.getName());
					System.out.println("服务端位置：" + file1.getAbsolutePath());

					file1.getParentFile().mkdir();
					file1.createNewFile();

					InputStream ins = fileItem.getInputStream();//..这里取二进制
					OutputStream ous = new FileOutputStream(file1);

					byte[] buffer = new byte[1024];

					System.out.println("容量为：" + fileItem.getSize());
					int len = 0;
					while ((len = ins.read(buffer)) > -1) {
						// System.out.println("len为："+len);
						ous.write(buffer, 0, len);
					}
					try {
						response.getWriter().write(
								"已保存文件" + file1.getAbsolutePath() + "<br/>");
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} finally {
						ous.close();
						ins.close();
					}
				}

			}

		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
